<template>
  <a-row :gutter="24" class="search-row">
    <x-card>
      <div slot="content" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-date-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  @change="onChange1"
                  :style="{ width: '100%' }"
                  v-model="TimeOn" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-date-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  @change="onChange2"
                  :style="{ width: '100%' }"
                  v-model="TimeEnd" />
              </a-form-item>
            </a-col>
            <a-col :span="8" style="margin-bottom: 3px;">
              <a-button type="primary" @click="handleClick" :loading="saving">查询</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </x-card>
    <a-row :gutter="48" class="search-row">
      <a-col :span="24">
        <a-divider orientation="left" style="font-weight: bold; margin-bottom: -2px;margin-top: -2px"> 相关方数据统计
        </a-divider>
        <a-card style="overflow-y: auto;" :bordered="false">
          <a-row style="width: 100%; height: 400px;">
            <a-col :span="2" class="search-buttons" style="margin-left: -5px; margin-bottom: 5px;">
              <a-button type="primary" @click="handleExportExcel" :loading="batchExportLoading"><a-icon type="export"/>导出</a-button>
            </a-col>
            <!-- <a-col :span="4">
              <a-progress
                v-if="batchExportLoading"
                :percent="exportProgress"
                status="active"
              />
            </a-col> -->
            <a-col :span="24">
              <a-table
                bordered
                :columns="columns"
                :dataSource="loadData"
                :alert="false"
                :pagination="false"
                :rowKey="(record, index) => record.organizationName"
              >
              </a-table>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </a-row>
</template>
<script>
import { STable, XCard, XDown } from '@/components'
import { getOverLappingTotalQuery } from '@/api/modular/system/QHSEXyViolation'
import moment from 'moment'
import * as XLSX from 'xlsx'
export default {
    components: {
      XDown,
      XCard,
      STable
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        queryParam: {
          TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
          TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        },
        batchExportLoading: false,
        TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
        TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
        saving: false,
        exportProgress: 0,
        // 表头
        columns: [
          {
            title: '检查单位',
            dataIndex: 'organizationName'
          },
          {
            title: '违章数量',
            dataIndex: 'violationCount'
          },
          {
            title: '隐患数量',
            dataIndex: 'dangerCount'
          },
          {
            title: '总计',
            dataIndex: 'totalCount'
          }
        ],
        loadData: []
        }
    },
    created() {
      this.select()
    },
    methods: {
        onChange1(date, dateString) {
            // console.log(dateString, date)
            if (this.queryParam.TimeEnd && dateString) {
              if (dateString > this.queryParam.TimeEnd) {
                this.$message.error('开始时间不能晚于结束时间')
                this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
                this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
                this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
                this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
              } else {
                this.queryParam.TimeOn = dateString
              }
            } else {
              this.queryParam.TimeOn = dateString
            }
          },
        onChange2(date, dateString) {
          if (this.queryParam.TimeOn && dateString) {
            if (this.queryParam.TimeOn > dateString) {
              this.$message.error('开始时间不能晚于结束时间')
              this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
              this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
              this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
              this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
            } else {
              this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
            }
          } else {
            this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
          }
        },
        handleClick() {
          if ((!this.TimeOn && !this.TimeEnd) || (this.TimeOn && this.TimeEnd)) {
            // 后端方法
            this.select()
          } else {
            this.$message.warning('请填写完整的查询条件')
          }
        },
        handleExportExcel() {
          this.batchExportLoading = true
          this.exportProgress = 0 // 重置进度
          const data = this.loadData.map(item => ({
            '检查单位': item.organizationName,
            '违章数量': item.violationCount,
            '隐患数量': item.dangerCount,
            '总计': item.totalCount
          }))
          const interval = setInterval(() => {
            if (this.exportProgress < 90) { // 进度最高到 90%，剩下的 10% 在下载完成时更新
              this.exportProgress += 10
            }
          }, 1000)
          const worksheet = XLSX.utils.json_to_sheet(data)
          const workbook = XLSX.utils.book_new()
          XLSX.utils.book_append_sheet(workbook, worksheet, '数据录入统计')
          const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
          const blob = new Blob([wbout], { type: 'application/octet-stream' })
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = '数据录入统计.xlsx'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          URL.revokeObjectURL(url)
          clearInterval(interval) // 清除定时器
          this.exportProgress = 100 // 导出完成后，设置进度为 100%
          clearInterval(interval)
           // 清除定时器
        },
        select() {
            // 后端方法
            this.saving = true
            getOverLappingTotalQuery(this.queryParam).then((res) => {
              this.loadData = res.data.rows
            })
            .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
        }
    }
}
</script>

<style lang="less" scoped>
/deep/.ant-table-tbody tr:last-child
 {
  background-color:#f5f5f5d6;
 }

</style>
